package com.example.movie.ui.video

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.fragment.app.viewModels
import androidx.viewpager.widget.ViewPager.SimpleOnPageChangeListener
import com.dueeeke.videoplayer.exo.ExoMediaPlayer
import com.dueeeke.videoplayer.player.VideoView
import com.dueeeke.videoplayer.util.L
import com.example.movie.R
import com.example.movie.data.video.factory.VideoRenderViewFactory
import com.example.movie.data.video.factory.VideoViewModelFactory
import com.example.movie.data.video.model.VideoViewModel
import com.example.movie.ui.video.adapter.VideoAdapter
import com.example.movie.ui.video.bean.VideoVo
import com.example.movie.ui.video.view.VerticalViewPager
import com.example.movie.utils.ContextHolder
import com.example.movie.utils.Utils
import com.example.movie.utils.cache.PreloadManager
import kotlinx.android.synthetic.main.fragment_video.*

/**
 *
 */
class VideoFragment : BaseVideoFragment<VideoView<*>>() {

    /**
     * 当前播放位置
     */
    private var mCurPos = 0

    //    private val mVideoList: MutableList<VideoBean> = ArrayList<VideoBean>()
    private val mVideoList: MutableList<VideoVo> = mutableListOf()
    private var mVideoAdapter: VideoAdapter? = null
    private var mViewPager: VerticalViewPager? = null
    private var mPreloadManager: PreloadManager? = null
    private var mController: VideoController? = null
    override val layoutResId: Int
        get() = R.layout.fragment_video

    private val videoViewModel: VideoViewModel by viewModels(factoryProducer = { VideoViewModelFactory() })
    private val loginViewModel = ContextHolder.getMainContext().loginViewModel


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requireActivity().window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        videoViewModel.getVideos()
        setVideoDataObserver()
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    private fun setVideoDataObserver() {
        videoViewModel.videoData.observe(viewLifecycleOwner, { it ->
            it?.success?.let {
                mVideoList.addAll(it)
                addData(null)
                mViewPager!!.post { startPlay(0) }
            }
        })
    }

    override fun initView() {
        super.initView()
        initViewPager()
        initVideoView()
        mPreloadManager = PreloadManager.getInstance(requireContext())
//        addData(null)

        val extras: Intent = requireActivity().intent
        val index = extras.getIntExtra(KEY_INDEX, 0)
        mViewPager!!.currentItem = index
        mViewPager!!.post { startPlay(index) }

    }

    private fun initVideoView() {
        mVideoView = VideoView<ExoMediaPlayer>(requireContext())
        mVideoView!!.setLooping(true)

        //以下只能二选一，看你的需求
        mVideoView!!.setRenderViewFactory(VideoRenderViewFactory.create())
        //        mVideoView.setScreenScaleType(VideoView.SCREEN_SCALE_CENTER_CROP);
        mController = VideoController(requireContext())
        mVideoView!!.setVideoController(mController)
    }

    private fun initViewPager() {
        mViewPager = vvp
        mViewPager!!.offscreenPageLimit = 4
        mVideoAdapter = VideoAdapter(mVideoList, videoViewModel,loginViewModel,this)
        mViewPager!!.adapter = mVideoAdapter
        mViewPager!!.overScrollMode = View.OVER_SCROLL_NEVER
        mViewPager!!.setOnPageChangeListener(object : SimpleOnPageChangeListener() {
            private var mCurItem = 0

            /**
             * VerticalViewPager是否反向滑动
             */
            private var mIsReverseScroll = false

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels)
                if (position == mCurItem) {
                    return
                }
                mIsReverseScroll = position < mCurItem
            }

            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                if (position == mCurPos) return
                startPlay(position)
            }

            override fun onPageScrollStateChanged(state: Int) {
                super.onPageScrollStateChanged(state)
                if (state == VerticalViewPager.SCROLL_STATE_DRAGGING) {
                    mCurItem = mViewPager!!.currentItem
                }
                if (state == VerticalViewPager.SCROLL_STATE_IDLE) {
                    mPreloadManager!!.resumePreload(mCurPos, mIsReverseScroll)
                } else {
                    mPreloadManager!!.pausePreload(mCurPos, mIsReverseScroll)
                }
            }
        })
    }

    private fun startPlay(position: Int) {
        val count = mViewPager!!.childCount
        for (i in 0 until count) {
            val itemView = mViewPager!!.getChildAt(i)
            val viewHolder: VideoAdapter.ViewHolder = itemView.tag as VideoAdapter.ViewHolder
            if (viewHolder.mPosition === position) {
                mVideoView!!.release()
                Utils.removeViewFormParent(mVideoView)
                val videoBean: VideoVo = mVideoList[position]
                val playUrl = mPreloadManager!!.getPlayUrl(videoBean.url!!)
                L.i("startPlay: position: $position  url: $playUrl")
                mVideoView!!.setUrl(playUrl)
                mController?.addControlComponent(viewHolder.mVideoView, true)
                viewHolder.mPlayerContainer.addView(mVideoView, 0)
                mVideoView!!.start()
                mCurPos = position
                break
            }
        }
    }

    private fun addData(view: View?) {
//        DataUtil.getTikTokDataFromAssets(requireContext())?.let { mVideoList.addAll(it) }
        mVideoAdapter?.notifyDataSetChanged()
    }

    override fun onDestroy() {
        super.onDestroy()
        mPreloadManager!!.removeAllPreloadTask()
        //清除缓存，实际使用可以不需要清除，这里为了方便测试
//        clearAllCache(requireContext())
    }


    companion object {

        private const val KEY_INDEX = "index"

        fun start(context: Context, index: Int) {
            val i = Intent(context, VideoFragment::class.java)
            i.putExtra(KEY_INDEX, index)
            context.startActivity(i)
        }

    }


    override fun onViewStateRestored(savedInstanceState: Bundle?) {
        super.onViewStateRestored(savedInstanceState)
        // TODO: 2021/1/25 恢复页面状态
    }

}